package controllers

import (
	"demo/models"
	"encoding/json"
	"errors"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"strings"
)

// OrderController operations for Order
type OrderController struct {
	beego.Controller
}

// URLMapping ...
func (c *OrderController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// Post ...
// @Title Post
// @Description create Order
// @Param	body		body 	models.Order	true		"body for Order content"
// @Success 201 {int} models.Order
// @Failure 403 body is empty
// @router / [post]
func (c *OrderController) Post() {

	//获取字符串时间，https://www.bbsmax.com/A/amd0mex2zg/
	/*time2 := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(time2)
	//时间戳
	fmt.Println(time.Now().Unix())
	//时间戳转换成日期
	fmt.Println(time.Unix(time.Now().Unix(), 0))
	//日期格式化
	fmt.Println(time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05"))
	//转换日期格式
	fmt.Println(time.Unix(time.Now().Unix(), 0).Format("01/02/2006"))
	return*/

	//form-data、x-www-form-urlencoded表单方式提交
	//var v2 models.Order
	//c.ParseForm(&v2)

	//raw，json方式提交
	//json.Unmarshal(c.Ctx.Input.RequestBody, &v2)
	//fmt.Println(v2)
	//return

	//时间格式转换
	//t := time.Now()
	//fmt.Println(t.Format("2006-01-02 15:04:05"))
	//return

	var v models.Order
	json.Unmarshal(c.Ctx.Input.RequestBody, &v)
	fmt.Println(v)
	if _, err := models.AddData(&v); err == nil {
		//if _, err := models.AddOrder(&v); err == nil {
		c.Ctx.Output.SetStatus(201)
		c.Data["json"] = "ok"
		//c.Data["json"] = v
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// GetOne ...
// @Title Get One
// @Description get Order by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Order
// @Failure 403 :id is empty
// @router /:id [get]
func (c *OrderController) GetOne() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 0, 64)
	v, err := models.GetData(id)
	//v, err := models.GetOrderById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get Order
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Order
// @Failure 403
// @router / [get]
func (c *OrderController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllOrder(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = l
	}
	c.ServeJSON()
}

// Put ...
// @Title Put
// @Description update the Order
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Order	true		"body for Order content"
// @Success 200 {object} models.Order
// @Failure 403 :id is not int
// @router /:id [put]
func (c *OrderController) Put() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 0, 64)
	v := models.Order{Id: id}
	json.Unmarshal(c.Ctx.Input.RequestBody, &v)
	fmt.Println(v)
	//if err := models.UpdateOrderById(&v); err == nil {
	//	c.Data["json"] = "OK"
	//} else {
	//	c.Data["json"] = err.Error()
	//}
	c.ServeJSON()
}

// Delete ...
// @Title Delete
// @Description delete the Order
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /:id [delete]
func (c *OrderController) Delete() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 0, 64)
	if rows, err := models.DeleteData(id); err == nil {
		//if err := models.DeleteOrder(id); err == nil {
		fmt.Println(rows)
		c.Data["json"] = "rows：" + strconv.Itoa(int(rows))
	} else {
		c.Data["json"] = err.Error()
	}
	c.ServeJSON()
}

// bulkData
// Desc: 批量插入
// User: zouqihui
// Date: 2022-12-07 10:55:01
// @receiver c
func (c *OrderController) BulkData() {
	if num, err := models.BulkData(); err == nil {
		c.Data["json"] = "bulk rows: " + strconv.Itoa(int(num))
	} else {
		c.Data["json"] = err.Error()
	}

	c.ServeJSON()
}

// Update ...
// @Title Update
// @Description update the Order
// @Param	id		path 	string	true		"The id you want to update"
// @Success 200 {string} update success!
// @Failure 403 id is empty
// @router /order/Put/:id [update]
func (c *OrderController) Update() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 0, 64)
	v := models.Order{Id: id}
	json.Unmarshal(c.Ctx.Input.RequestBody, &v)

	fmt.Println(v)

	//if num, err := models.UpdateData(&v); err == nil {
	//	c.Data["json"] = "update rows: " + strconv.Itoa(int(num))
	//} else {
	//	c.Data["json"] = err.Error()
	//}

	c.ServeJSON()
}

// RawQuery
// Desc:
// User: zouqihui
// Date: 2022-12-08 10:42:27
// @receiver c
func (c *OrderController) RawQuery() {

	v, err := models.RawQuery()
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()

}

// GormQuery
// Desc: gorm查询操作
// User: zouqihui
// Date: 2022-12-08 16:22:44
// @receiver c
func (c *OrderController) GormQuery() {
	idStr := c.Ctx.Input.Param(":id")
	id, _ := strconv.ParseInt(idStr, 0, 64)
	data, err := models.GormQuery(id)
	if err == nil {
		c.Data["json"] = data
	} else {
		c.Data["json"] = err.Error()
	}

	c.ServeJSON()
}
